import { subject } from '@/api/subject'

export default {
  namespaced: true,
  state: {
    idList: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    total: 0,
    filterParams: {
      categoryId: '',
      subjectName: '',
      subjectType: '',
      subjectLevel: ''
    }
  },
  mutations: {
    ADD_IDS(state, ids) {
      state.idList = [...state.idList, ...ids]
    },
    CLEAR_IDS(state) {
      state.idList = []
    },
    SET_PAGE(state, page) {
      state.currentPage = page
    },
    SET_TOTAL(state, total) {
      state.total = total
      state.hasMore = state.idList.length < total
    },
    SET_FILTER_PARAMS(state, params) {
      state.filterParams = { ...params }
    }
  },
  actions: {
    async loadMoreIds({ state, commit }) {
      try {
        const res = await subject.getPage({
          page: state.currentPage + 1,
          pageSize: state.pageSize,
          ...state.filterParams
        })
        
        if (res.code === 200) {
          const newIds = res.content.list.map(item => item.id)
          commit('ADD_IDS', newIds)
          commit('SET_PAGE', state.currentPage + 1)
          commit('SET_TOTAL', parseInt(res.content.total))
        }
      } catch (error) {
        console.error('加载更多ID失败:', error)
      }
    },
    
    initIdList({ commit }, { ids, total, filterParams }) {
      commit('CLEAR_IDS')
      commit('ADD_IDS', ids)
      commit('SET_PAGE', 1)
      commit('SET_TOTAL', total)
      if (filterParams) {
        commit('SET_FILTER_PARAMS', filterParams)
      }
    }
  },
  getters: {
    getNavigation: (state) => (currentId) => {
      const currentIndex = state.idList.indexOf(currentId)
      return {
        prevId: currentIndex > 0 ? state.idList[currentIndex - 1] : null,
        nextId: currentIndex < state.idList.length - 1 ? state.idList[currentIndex + 1] : null,
        isLastItem: currentIndex === state.idList.length - 1
      }
    }
  }
} 